package com.shigen.demo.atguigu;

import java.util.concurrent.TimeUnit;

/**
 * 死锁案例
 *
 * @author shigenfu
 * @date 2022/5/25 5:41 下午
 */

class HoldLockThread implements Runnable {

  private String lockA;
  private String lockB;

  public HoldLockThread(String lockA, String lockB) {
    this.lockA = lockA;
    this.lockB = lockB;
  }

  @Override
  public void run() {
    synchronized (lockA) {
      System.out.println(Thread.currentThread().getName() +
          "\t自己持有：" + lockA + "\t 尝试获得：" + lockB);
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (lockB) {
        System.out.println(Thread.currentThread().getName() +
            "\t自己持有：" + lockB + "\t 尝试获得：" + lockA);
      }
    }
  }
}



public class DeadLockDemo {

  public static void main(String[] args) {
    String lockA = "lockA";
    String lockB = "lockB";

    new Thread(new HoldLockThread(lockA, lockB), "threadAA").start();
    new Thread(new HoldLockThread(lockB, lockA), "threadBB").start();
  }
}
